/**
 * Created by wd14931 on 2017/5/23.
 *
 *
 */
var http = require("http");
var iconv   = require('iconv-lite');
var query   = require('querystring');

module.exports = function (option){

    var option = option;

    var _data = option.data? option.data : false;

    _data && delete option.data;

    return new Promise(function (resolve, reject) {

        var _req = http.request(option, function (res) {

            var chunks = [];
            var size = 0;

            // 请求回流
            res.on('data', function (chunk) {

                chunks.push(chunk)
                size += chunk.length;
            });

            // res 结束
            res.on('end', function () {

                var buf = Buffer.concat(chunks, size);
                var str = iconv.decode(buf, 'utf-8');

                resolve([null, str]);
            });
        });

        _req.on('error', function (e) {
            console.log('problem with '+option.path+' request: ' + e.message);
            
            resolve([e, '']);
        });

        option['method'].toLocaleUpperCase() === 'POST' && _data && _req.write(query.stringify(_data));

        _req.end();
    })
};
